package com.spark.trouble.agency

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import com.spark.trouble.MajorAgencyInfoModel
import com.spark.trouble.R
import com.spark.trouble.UploadFileAdapter
import kotlinx.android.synthetic.main.frag_handle_schema.*

/**
 * [待办] -> 现场治理/重大治理任务 -> 待审核 -> 治理方案
 */
class HandleSchemaFragment : BaseFragment() {
    private var taskId: String = ""
    private lateinit var fileAdapter: UploadFileAdapter

    companion object {
        fun newInstance(taskId: String): HandleSchemaFragment {
            val target = HandleSchemaFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_handle_schema
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@HandleSchemaFragment.taskId = this
                fetchInfo(taskId)
            }
        }
        // 驳回
        tv_reject.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank()) {
                                alert("请输入驳回理由")
                            } else {
                                d.dismiss()
                                submitReject(this@HandleSchemaFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
                        .create()
                        .show()
            }
        }
        // 通过
        btn_resolve.setOnClickListener { submitResolve(taskId) }
        fileAdapter = UploadFileAdapter(R.layout.item_rectify_upload_file).apply {
            setOnItemChildClickListener { adapter, view, position ->
                val file = fileAdapter.data[position]
                when (view.id) {
                    R.id.iv_glance -> {
                        toast("查找文件 【${file.fileName}】")
                    }
                    R.id.iv_delete -> {
                        fileAdapter.remove(position)
                    }
                }
            }
        }
        recy_files.apply {
            adapter = fileAdapter
            layoutManager = object : LinearLayoutManager(context) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun fetchInfo(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agencty_major_fetch_verify}", mutableMapOf("taskId" to taskId).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            val gson = Gson()
                            gson.fromJson(it, MajorAgencyInfoModel::class.java)?.apply {
                                if (code == "200" && resultMaps.isNotEmpty()) {
                                    resultMaps[0].apply {
                                        // todo restore

                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }

    /**
     * [待办] 待审核 -> 通过
     */
    @SuppressLint("CheckResult")
    private fun submitResolve(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_major_submit_verify}", mutableMapOf("taskId" to taskId, "approveState" to "2").toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )

    }

    @SuppressLint("CheckResult")
    private fun submitReject(taskId: String, reason: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", mutableMapOf("taskId" to taskId, "refuseReason" to reason).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中")
                        }
                )
    }

}